﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EasyStep.Business.Providers;
using EasyStep.Data.Entities;
using EasyStep.Business.Interfaces;
namespace EasyStep.Business.Managers
{
    public class BaseDataManager<TProvider, TEntity>
        where TProvider : IDataProvider<TEntity>
        where TEntity : Entity
    {
        public TProvider Provider { get; set; }
        public BaseDataManager(TProvider provider)
        {
            Provider = provider;
        }
      
        public virtual TEntity Create(TEntity data)
        {
            return Provider.Create(data);
        }
        public virtual TEntity Update(TEntity data)
        {
            return Provider.Update(data);
        }
        public virtual TEntity Delete(TEntity data)
        {
            return Provider.Delete(data);
        }

        public T GetOrCreateItemByName<T>(string itemNameOrId, Func<IEnumerable<T>> getAllAvailable, Func<T> onNotFound = null)
            where T:NamedEntity
        {
            T result = null;
            //by id 
            //Guid prId;
            //if (Guid.TryParse(itemNameOrId, out prId) && !prId.Equals(Guid.Empty))
            //    result = Get(prId) as T;
            //if (result != null || string.IsNullOrEmpty(itemNameOrId)) return result;

            //by name     
            var existingItems =getAllAvailable();
            result = existingItems.Where(i => i.Name.Equals(itemNameOrId, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
            if (result != null) return result;

            var tResult = onNotFound();
            result = Create(tResult as TEntity) as T;

            return result;
        }
    }
}
